<template>
  <div>
    <input type="file" @change="handleFileUpload">
    <div class="imgFrame">
      <img id="imgUploaded" :src="src" alt="图片上传">
    </div>
    <input type="button" value="dialog" @click="clickBtn">
    <DDialog v-if="propsItem.isMask" :propsItem="propsItem" @child-ok="childok" @child-cancel="childcancel">
      这里是一条提醒
    </DDialog>
  </div>
</template>

<script>
import DDialog from './components/DDialog.vue'
import axios from 'axios'

export default {
  name: "App",
  components: {
    DDialog
  },
  data() {
    return {
      propsItem: {
        title: '我是dialog标题',
        ok: '我是确认按钮',
        cancel: '我是取消按钮',
        isMask: false,
      },
      src: ''
    };
  },
  methods: {
    clickBtn() {
      this.propsItem.isMask = true;
      console.log(Date.now())
    },
    childok() {
      alert('确认被点击')
      this.propsItem.isMask = false
    },
    childcancel() {
      this.propsItem.isMask = false
    },

    handleFileUpload(event) {
      const file = event.target.files[0];
      const formData = new FormData(); // 创建一个FormData对象
      formData.append('image', file); // 将选中的文件添加到FormData对象中，'image'为图片文件的键名

      console.log(file);
      console.log(formData);
      console.log(formData.get('image'));
      for (let key of formData.keys()) {
        console.log(key);
      }

      const that = this;
      if (!event || !window.FileReader) return; // 看是否支持FileReader
      const reader = new FileReader();
      reader.readAsDataURL(file); // 转换为url
      reader.onloadend = function () {
        that.src = this.result;//将转换完成的url赋给src
      }

      // 发送POST请求，上传文件
      axios.post('127.0.0.1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data' // 设置请求头的Content-Type为multipart/form-data
        }
      }).then(response => {
        // 处理上传成功的响应
        console.log('上传成功')
        console.log(response.data)
      }).catch(err => {
        // 处理上传失败的错误
        console.log(err)
      });

      // let config = {
      //   method: 'post',
      //   url: '127.0.0.1',
      //   headers: {
      //     'Content-Type': 'multipart/form-data',
      //   },
      //   data: formData
      // };
      // axios(config)
      //   .then(function (response) {
      //     console.log(JSON.stringify(response.data));
      //   })
      //   .catch(function (error) {
      //     console.log(error);
      //   });
    }
  }
};
</script>

<style scoped>
img[src=""],
/* 图片未上传时，不让img标签显示图裂图标和alt */
img:not([src]) {
  opacity: 0;
}

.imgFrame {
  height: 150px;
  width: 400px;
  overflow: hidden;

  object-fit: contain;
}

#imgUploaded {
  object-fit: cover;
}
</style>